from fastapi import Depends, Header, Request
from jose import JWTError, jwt
from typing import Dict, Any, Optional
import logging
from datetime import datetime, timedelta, UTC
import os
import sys
from core.config import settings
from core.exception import ApiException

logger = logging.getLogger(__name__)


def remove_prefix(token_ai_pan: str) -> str:
    """移除token的前缀"""
    return token_ai_pan.replace(settings.JWT_LOGIN_SUBJECT, "").strip() if token_ai_pan.startswith(
        settings.JWT_LOGIN_SUBJECT) else token_ai_pan


async def get_current_user(request: Request, token: str = Header(None), token_ai_pan: str = Header(None)) -> Dict[str, Any]:
    """
    获取当前用户信息

    Args:
        token: JWT token字符串，从请求头中获取

    Returns:
        Dict[str, Any]: 包含用户信息的字典，格式为 {"account_id": int, "username": str}

    Raises:
        ApiException: 当token无效、过期或解析失败时抛出异常
        :param token_ai_pan:
        :param token:
        :param token:

    """
    try:
        # 筛选两个不同，避免报错

        print(token)
        print(token_ai_pan)


        # 验证token是否存在
        if not token or not token.strip():
            token = token_ai_pan
            # 如果请求头中都没有，尝试从请求体获取
            if not token or not token.strip():
                try:
                    # 尝试从请求体获取token
                    body_data = await request.body()
                    if body_data:
                        import json
                        body_dict = json.loads(body_data)
                        # 检查请求体中是否有token或token_ai_pan字段
                        token = body_dict.get('token') or body_dict.get('token_ai_pan')
                        logger.info(f"从请求体获取token: {token is not None}")
                except Exception as e:
                    logger.warning(f"解析请求体失败: {str(e)}")
                    # 解析失败不影响，继续使用None
                    pass
                
                if not token or not token.strip():
                    logger.error("Token不能为空")
                    raise ApiException(msg="Token不能为空", code=-1)




        # 移除前缀并解析token
        token = remove_prefix(token.strip())
        payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])

        # 验证token内容
        if payload.get("sub") != settings.JWT_LOGIN_SUBJECT or not payload.get("accountNo"):
            raise ApiException(msg="无效的认证凭据", code=-1)

        # 记录日志并返回用户信息
        logger.info(f"JWT解密成功，accountNo: {payload.get('accountNo')}, username: {payload.get('username')}")
        return {"accountNo": payload.get("accountNo"), "username": payload.get("username")}

    except Exception as e:
        logger.error(f"JWT处理失败: {str(e)}")
        raise ApiException(msg="无效的认证凭据", code=-1)